//
//  CommonCrypto.swift
//  KCSwift
//
//  Created by apple on 2023/11/17.
//

import Foundation
import CommonCrypto

extension String {
    func aesEncrypt(key: String) -> String? {
        if let keyData = key.data(using: .utf8),
           let data = self.data(using: .utf8),
           let cryptData = NSMutableData(length: Int((data.count / kCCBlockSizeAES128 + 1) * kCCBlockSizeAES128)) {

            let keyLength = size_t(kCCKeySizeAES256)
            let operation = CCOperation(kCCEncrypt)
            let algoritm = CCAlgorithm(kCCAlgorithmAES)
            let options = CCOptions(kCCOptionPKCS7Padding | kCCOptionECBMode)
            var numBytesEncrypted: size_t = 0

            let cryptStatus = CCCrypt(operation,
                                      algoritm,
                                      options,
                                      (keyData as NSData).bytes, keyLength,
                                      nil,
                                      (data as NSData).bytes, data.count,
                                      cryptData.mutableBytes, cryptData.length,
                                      &numBytesEncrypted)

            if UInt32(cryptStatus) == UInt32(kCCSuccess) {
                cryptData.length = Int(numBytesEncrypted)
                let base64cryptString = cryptData.base64EncodedString()
                return base64cryptString
            }
        }
        return nil
    }

    func aesDecrypt(key: String) -> String? {
        if let keyData = key.data(using: .utf8),
           let data = Data(base64Encoded: self),
           let cryptData = NSMutableData(length: Int((data.count / kCCBlockSizeAES128 + 1) * kCCBlockSizeAES128)) {

            let keyLength = size_t(kCCKeySizeAES256)
            let operation = CCOperation(kCCDecrypt)
            let algoritm = CCAlgorithm(kCCAlgorithmAES)
            let options = CCOptions(kCCOptionPKCS7Padding | kCCOptionECBMode)

            var numBytesEncrypted: size_t = 0

            let cryptStatus = CCCrypt(operation,
                                      algoritm,
                                      options,
                                      (keyData as NSData).bytes, keyLength,
                                      nil,
                                      (data as NSData).bytes, data.count,
                                      cryptData.mutableBytes, cryptData.length,
                                      &numBytesEncrypted)

            if UInt32(cryptStatus) == UInt32(kCCSuccess) {
                cryptData.length = Int(numBytesEncrypted)
                let unencryptedMessage = String(data: cryptData as Data, encoding: .utf8)
                return unencryptedMessage
            }
        }
        return nil
    }
}




